package com.mrart.common.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanUtils {
    
 // Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
    public static Map<String, Object> transBean2Map(Object ...objs) {
        if(objs== null){
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        for(Object obj:objs){
            if(obj== null){
                continue;
            }
            try {
                    BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
                    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                    for (int i=0;i<propertyDescriptors.length;i++) {
                        String key = propertyDescriptors[i].getName();
        
                        // 过滤class属性
                        if (!key.equals("class") && !key.equals("callbacks")) {
                            // 得到property对应的getter方法
                            Method getter = propertyDescriptors[i].getReadMethod();
                            if(getter!=null){
                                Object value = getter.invoke(obj);
                                if(value != null){
                                    map.put(key, value);
                                }else{
                                    map.put(key, null);
                                }
                            }
                        }
                    }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("transBean2Map Error " + e);
            }
        }
        return map;
    }
}
